<template>
  <div class="cart-page">
    <!-- 购物车主体 -->
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h2 class="text-lg font-medium">我的购物车</h2>
          <div class="flex items-center space-x-2">
            <el-button
              @click="handleBatchCollect"
              :disabled="selectedItems.length === 0"
            >
              移入收藏
            </el-button>
            <el-button
              type="primary"
              @click="handleCheckout"
              :disabled="selectedItems.length === 0"
            >
              结算 ({{ selectedItems.length }})
            </el-button>
          </div>
        </div>
      </template>

      <!-- 购物车列表 -->
      <div class="cart-list">
        <template v-if="cartItems.length === 0">
          <div class="empty-cart">
            <el-empty description="购物车还是空的">
              <template #image>
                <img
                  src="/images/empty-cart.png"
                  class="w-40 h-40"
                  alt="空购物车"
                />
              </template>
              <template #description>
                <p class="text-gray-500 mb-4">购物车还是空的，去逛逛吧~</p>
              </template>
              <el-button type="primary" @click="router.push('/shop')"
                >去购物</el-button
              >
            </el-empty>
          </div>
        </template>

        <template v-else>
          <div
            class="cart-header flex items-center py-2 border-b text-gray-500 mb-4"
          >
            <div class="w-12">
              <el-checkbox
                v-model="selectAll"
                @change="handleSelectAll"
                :indeterminate="isIndeterminate"
              />
            </div>
            <div class="flex-1">商品信息</div>
            <div class="w-24 text-center">单价</div>
            <div class="w-32 text-center">数量</div>
            <div class="w-24 text-center">小计</div>
            <div class="w-32 text-center">操作</div>
          </div>

          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <div
              class="item-content flex items-center py-4 border-b hover:bg-gray-50 transition-colors"
            >
              <div class="w-12">
                <el-checkbox
                  v-model="item.selected"
                  @change="handleItemSelect"
                />
              </div>
              <div class="flex-1 flex items-center">
                <el-image
                  :src="item.image"
                  class="w-20 h-20 object-cover rounded cursor-pointer"
                  @click="viewProduct(item)"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="ml-4 flex-1">
                  <h3
                    class="text-base font-medium mb-1 cursor-pointer hover:text-primary-500"
                    @click="viewProduct(item)"
                  >
                    {{ item.name }}
                  </h3>
                  <div class="flex items-center text-sm text-gray-500 mb-2">
                    <span class="mr-4">{{ item.specs }}</span>
                    <el-tag size="small" v-if="item.stock <= 5" type="warning"
                      >库存紧张</el-tag
                    >
                  </div>
                  <div class="text-xs text-gray-400" v-if="item.promotion">
                    <el-tag size="small" type="danger" class="mr-2"
                      >促销</el-tag
                    >
                    {{ item.promotion }}
                  </div>
                </div>
              </div>
              <div class="w-24 text-center">
                <template v-if="item.originalPrice > item.price">
                  <div class="text-xs text-gray-400 line-through">
                    ¥{{ item.originalPrice.toFixed(2) }}
                  </div>
                </template>
                <div class="text-primary font-medium">
                  ¥{{ item.price.toFixed(2) }}
                </div>
              </div>
              <div class="w-32 text-center">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.stock"
                  :step="1"
                  @change="(val) => handleQuantityChange(item, val)"
                  @focus="handleQuantityFocus(item)"
                />
              </div>
              <div class="w-24 text-center">
                <span class="text-primary font-medium"
                  >¥{{ (item.price * item.quantity).toFixed(2) }}</span
                >
              </div>
              <div class="w-32 text-center space-x-2">
                <el-button type="primary" text @click="handleCollect(item)">
                  <el-icon><Star /></el-icon>
                  <span>收藏</span>
                </el-button>
                <el-button type="danger" text @click="handleRemoveItem(item)">
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </el-button>
              </div>
            </div>
          </div>
        </template>
      </div>
    </el-card>

    <!-- 底部结算栏 -->
    <div
      class="cart-footer bg-white p-4 rounded-lg shadow-sm flex justify-between items-center sticky bottom-0"
    >
      <div class="flex items-center">
        <el-checkbox
          v-model="selectAll"
          @change="handleSelectAll"
          :indeterminate="isIndeterminate"
        >
          全选
        </el-checkbox>
        <el-button
          type="danger"
          text
          class="ml-4"
          @click="handleBatchRemove"
          :disabled="selectedItems.length === 0"
        >
          删除选中
        </el-button>
        <el-button
          type="primary"
          text
          class="ml-4"
          @click="handleBatchCollect"
          :disabled="selectedItems.length === 0"
        >
          移入收藏
        </el-button>
      </div>
      <div class="flex items-center">
        <div class="mr-8 text-sm">
          <span class="text-gray-500"
            >已选商品 {{ selectedItems.length }} 件</span
          >
          <template v-if="totalDiscount > 0">
            <span class="mx-4 text-gray-500">总优惠：</span>
            <span class="text-danger">-¥{{ totalDiscount.toFixed(2) }}</span>
          </template>
          <span class="ml-4">合计：</span>
          <span class="text-primary text-xl font-medium"
            >¥{{ totalAmount.toFixed(2) }}</span
          >
        </div>
        <el-button
          type="primary"
          size="large"
          @click="handleCheckout"
          :disabled="selectedItems.length === 0"
        >
          结算
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Star, Delete, Picture } from "@element-plus/icons-vue";

const router = useRouter();

// 购物车数据
const cartItems = ref([
  {
    id: 1,
    name: "贵港特色手工艺品",
    specs: "传统手工编织",
    price: 99.0,
    originalPrice: 129.0,
    quantity: 1,
    stock: 10,
    image: "/images/products/product1.jpg",
    selected: false,
    promotion: "限时优惠：满200减30",
  },
  {
    id: 2,
    name: "贵港特产礼盒",
    specs: "年货礼盒装",
    price: 299.0,
    originalPrice: 299.0,
    quantity: 1,
    stock: 3,
    image: "/images/products/product2.jpg",
    selected: false,
  },
]);

// 全选状态
const selectAll = ref(false);
const isIndeterminate = computed(() => {
  const selectedCount = cartItems.value.filter((item) => item.selected).length;
  return selectedCount > 0 && selectedCount < cartItems.value.length;
});

// 选中的商品
const selectedItems = computed(() =>
  cartItems.value.filter((item) => item.selected),
);

// 总金额
const totalAmount = computed(() => {
  return selectedItems.value.reduce(
    (total, item) => total + item.price * item.quantity,
    0,
  );
});

// 总优惠金额
const totalDiscount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.originalPrice - item.price) * item.quantity;
  }, 0);
});

// 全选/取消全选
const handleSelectAll = (val) => {
  cartItems.value.forEach((item) => (item.selected = val));
};

// 单个商品选择
const handleItemSelect = () => {
  const selectedCount = cartItems.value.filter((item) => item.selected).length;
  selectAll.value = selectedCount === cartItems.value.length;
  isIndeterminate.value =
    selectedCount > 0 && selectedCount < cartItems.value.length;
};

// 修改商品数量
const handleQuantityChange = (item, val) => {
  if (val > item.stock) {
    ElMessage.warning(`该商品库存仅剩 ${item.stock} 件`);
    item.quantity = item.stock;
    return;
  }
  // TODO: 调用API更新购物车商品数量
  ElMessage.success("数量已更新");
};

// 数量输入框聚焦时记录原值
const handleQuantityFocus = (item) => {
  item._prevQuantity = item.quantity;
};

// 查看商品详情
const viewProduct = (product) => {
  router.push(`/shop/product/${product.id}`);
};

// 收藏单个商品
const handleCollect = async (item) => {
  try {
    // TODO: 调用收藏API
    ElMessage.success("已加入收藏");
  } catch (error) {
    ElMessage.error("收藏失败");
  }
};

// 批量收藏
const handleBatchCollect = async () => {
  if (selectedItems.value.length === 0) return;

  try {
    await ElMessageBox.confirm("确定将选中的商品加入收藏吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    });
    // TODO: 调用批量收藏API
    ElMessage.success("已加入收藏");
  } catch {
    // 用户取消操作
  }
};

// 删除单个商品
const handleRemoveItem = async (item) => {
  try {
    await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    cartItems.value = cartItems.value.filter((i) => i.id !== item.id);
    ElMessage.success("商品已删除");
  } catch {
    // 用户取消操作
  }
};

// 批量删除
const handleBatchRemove = async () => {
  if (selectedItems.value.length === 0) return;

  try {
    await ElMessageBox.confirm("确定要删除选中的商品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    cartItems.value = cartItems.value.filter((item) => !item.selected);
    ElMessage.success("选中商品已删除");
  } catch {
    // 用户取消操作
  }
};

// 结算
const handleCheckout = () => {
  if (selectedItems.value.length === 0) return;

  // 检查库存
  const insufficientItems = selectedItems.value.filter(
    (item) => item.quantity > item.stock,
  );
  if (insufficientItems.length > 0) {
    ElMessage.error("部分商品库存不足，请修改数量");
    return;
  }

  // TODO: 跳转到结算页面
  router.push({
    path: "/order/checkout",
    query: {
      items: selectedItems.value.map((item) => ({
        id: item.id,
        quantity: item.quantity,
      })),
    },
  });
};

// 页面加载时获取数据
onMounted(async () => {
  // TODO: 获取购物车数据
});
</script>

<style lang="scss" scoped>
.cart-page {
  @apply pb-20;

  .empty-cart {
    @apply py-12;
  }

  .cart-item {
    .image-slot {
      @apply flex items-center justify-center w-full h-full bg-gray-100;

      .el-icon {
        @apply text-3xl text-gray-400;
      }
    }
  }

  .cart-footer {
    @apply z-10;
  }
}
</style>
